package com.runa.rccprotocol.analysis;

import com.runa.protocol.analysis.MetaBufferAnalysis;
import com.runa.protocol.analysis.ShellBufferAnalysis;
import com.runa.protocol.dto.IInterData;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.dto.ConcentratorElectric;
import com.runa.rccprotocol.dto.ConcentratorResponseData;
import com.runa.rccprotocol.dto.equdata.ConcenReportData;
import com.runa.rccprotocol.dto.huizhong.HuiZhongHeartBeat;

/**
 * 汇中41系列协议解析器
 */
public class HuiZhong41Analysis extends ShellBufferAnalysis<byte[]> {

    public HuiZhong41Analysis(MetaBufferAnalysis analysis) {
        super(analysis, 0);
    }

    @Override
    public int fill(byte[] data, int length,String n) {
        interData = null;
        if (length == 1 && data[0] == 0x2a) {
            interData = new HuiZhongHeartBeat(netEquNo);
        }
        if (length < 6) {
            return -1;
        }
        int begin;
        for (begin = 0;begin < length;begin++) {
            if ((data[begin]&0xff) == 0x40
                    && data[begin+1] == 0x3a) {
                break;
            }
        }
        int L = (data[begin+2] << 8) + (data[begin+3] & 0xff);
        if (length < L + 6) {
            return -1;
        } else if (data[begin + L + 3] == ByteUtil.sum(data, begin+2, L+1)) {
            String id = ByteUtil.byteToHexString(data, begin+4, 6).replace("F", "");
            netEquNo = id;
            int code = data[begin+10];
            switch (code) {
                case 0x01:
                    register(id, data, begin+11);
                    break;
                case 0x2a:
                    interData = new HuiZhongHeartBeat(id);
                    break;
                case 0x06:
                    byte[] bs = new byte[L - 8];
                    System.arraycopy(data, begin+10, bs, 0, bs.length);
                    analysis.fill(bs, bs.length,netEquNo);
                    ConcentratorResponseData responseData = (ConcentratorResponseData) analysis.gain();
                    responseData.setAddress(id);
                    responseData.setUpward(true);
                    interData = responseData;
                    break;
            }
        }
        return length - L - 6;
    }

    private void register(String id, byte[] data, int offset) {
        ConcentratorElectric electric = new ConcentratorElectric(id);
        ConcenReportData reportData = new ConcenReportData();
        reportData.setElectric((float) ((data[offset++]&0xff) * 0.1));
        reportData.setCsq(data[offset]&0xff);
        electric.setReportData(reportData);
        interData = electric;
    }

    public static void main(String[] args) {
        byte[] hex = ByteUtil.hexStringToByte("40 3A 00 16 13 51 11 11 11 1F 01 59 18 41 03 00 00 00 00 26 02 40 09 41 05 39 0D 0A");
        HuiZhong41Analysis analysis = new HuiZhong41Analysis(new HZDeviceAnalysis());
        analysis.fill(hex, hex.length,"");
        analysis.gain();
    }

}
